package com.authine.cloudpivot.ext.service.impl;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.authine.cloudpivot.engine.api.facade.OrganizationFacade;
import com.authine.cloudpivot.engine.api.model.organization.DepartmentModel;
import com.authine.cloudpivot.engine.api.model.organization.DepartmentUserModel;
import com.authine.cloudpivot.engine.api.model.organization.UserModel;
import com.authine.cloudpivot.engine.enums.status.UserStatus;
import com.authine.cloudpivot.engine.enums.type.DeptType;
import com.authine.cloudpivot.ext.service.IdaasOrgSyncService;
import com.authine.cloudpivot.web.api.helper.oraganization.UserHelper;
import com.authine.cloudpivot.web.api.service.EngineService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.crypto.factory.PasswordEncoderFactories;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @Description
 * @Author fj
 * @Date 2022/05/16
 */
@Slf4j
@Service
public class IdaasOrgSyncServiceImpl implements IdaasOrgSyncService {
    @Autowired
    private EngineService engineService;

    @Value("${idaas.cloudpivotRootDeptId}")
    private String cloudpivotRootDeptId;
    private static final String MAIN = "main";

    @Override
    public void departmentAdd(JSONObject requestBody, String clientId) throws Exception {
        log.info("===idaas推送同步===新增组织=======requestBody:{}", requestBody.toJSONString());
        handlerOrg(null, requestBody);
    }

    @Override
    public void departmentUpdate(JSONObject requestBody, String clientId) throws Exception {
        log.info("===idaas推送同步===更新组织=======requestBody:{}", requestBody.toJSONString());
        //组织id
        String organizationUuid = requestBody.getString("organizationUuid");
        DepartmentModel model = this.engineService.getOrganizationFacade().getDepartmentBySourceId("CP" + organizationUuid);;
        handlerOrg(model, requestBody);
    }

    @Override
    public void departmentDelete(String id) {
        log.info("===idaas推送同步===删除组织=======id:{}", id);
        //根据部门查找部门
        DepartmentModel model = engineService.getOrganizationFacade().getDepartmentBySourceId("CP" + id);

        if (model != null) {
            model.setDeleted(Boolean.TRUE);
            engineService.getOrganizationFacade().updateDepartment(model);
        } else {
            log.info("===idaas推送同步===删除组织====组织不存在=======id:{}", id);
        }
    }

    private void handlerOrg(DepartmentModel model, JSONObject requestBody) throws Exception {

        try {
            //父级组织id
            String parentUuid = requestBody.getString("parentUuid");
            //组织名称
            String organization = requestBody.getString("organization");
            //组织id
            String organizationUuid = requestBody.getString("organizationUuid");
            //部门排序号
            Long levelNumber = requestBody.getLong("levelNumber");
            Boolean enabled = requestBody.getBoolean("enabled");
            //组织机构的管理者,value是管理者账户的外部ID,displayName是用户名,管理者可为空
            JSONArray manager = requestBody.getJSONArray("manager");

            OrganizationFacade organizationFacade = engineService.getOrganizationFacade();

            DepartmentModel pm;
            //如果parentUuid是main，做特殊处理
            if (MAIN.equals(parentUuid)) {
                pm = organizationFacade.getDepartment(cloudpivotRootDeptId);
            } else {
                pm = organizationFacade.getDepartmentBySourceId("CP" + parentUuid);
            }
            //将父级修改为非叶子节点
            if (pm != null && pm.getLeaf()) {
                pm.setLeaf(Boolean.FALSE);
                engineService.getOrganizationFacade().updateDepartment(pm);
            }
            String parentId = Optional.ofNullable(pm).orElse(new DepartmentModel()).getId();

            Boolean isAdd = Boolean.FALSE;
            //为空新增
            if (model == null) {
                isAdd = Boolean.TRUE;
                model = new DepartmentModel();
                model.setDeptType(DeptType.DEPT);
                model.setCorpId("main");
            }

            model.setDeleted(Boolean.FALSE);
            model.setEnabled(enabled);
            model.setName(organization);
            model.setParentId(parentId);
            model.setSortKey(levelNumber);
            model.setSourceId("CP" + organizationUuid);
            //if (!manager.isEmpty()) {
            //    JSONObject jsonObject = manager.getJSONObject(0);
            //    model.setManagerId((String) jsonObject.get("value"));
            //}
            //新建时默认是叶子节点
            if (isAdd) {
                model.setLeaf(Boolean.TRUE);
                log.info("===idaas推送同步===组织======={}==走新增", organization);
                model.setCreatedTime(new Date());
                organizationFacade.addDepartment(model);
            } else {
                log.info("===idaas推送同步===组织======={}==走更新", organization);
                //获取该部门旧的部门id
                String oldDepartmentParentId = model.getParentId();
                model.setModifiedTime(new Date());
                organizationFacade.updateDepartment(model);
                if (StringUtils.isNotBlank(oldDepartmentParentId)) {
                    //查询旧的部门下是否还存在子部门
                    List<DepartmentModel> departmentsByParentId = organizationFacade.getDepartmentsByParentId(oldDepartmentParentId);
                    if (departmentsByParentId.size() > 0) {
                        System.out.println("还存在子部门");
                    } else {
                        DepartmentModel department = organizationFacade.getDepartment(oldDepartmentParentId);
                        department.setLeaf(true);
                        organizationFacade.updateDepartment(department);
                    }
                }
            }

        } catch (Exception e) {
            log.error("===idaas推送同步====组织处理异常======{}", e.getMessage());
            throw new Exception("idaas推送同步组织,处理异常");
        }
    }

    @Override
    public void userAdd(JSONObject requestBody) throws Exception {
        log.info("===idaas推送同步===新增用户=======requestBody:{}", requestBody.toJSONString());
        this.handlerUser(requestBody);
    }

    @Override
    public void userUpdate(JSONObject requestBody) throws Exception {
        log.info("===idaas推送同步===更新用户=======requestBody:{}", requestBody.toJSONString());
        this.handlerUser(requestBody);
    }

    @Override
    public void userDelete(String id, String mainCorpId) {
        log.info("===idaas推送同步===删除用户=======id:{}", id);
        //根据主部门corpId查找用户
        UserModel user = engineService.getOrganizationFacade().getUserByUserIdAndCorpId(id, "main");
        if (user != null) {
            UserHelper userHelper = new UserHelper(engineService, mainCorpId);
            userHelper.delete(user.getId());
        } else {
            log.info("===idaas推送同步===删除用户====用户不存在=======id:{}", id);
        }
    }

    private void handlerUser(JSONObject requestBody) throws Exception {
        try {
            //用户ID,与外部ID值一样
            String id = requestBody.getString("id");
            //云IDaaS平台主账户
            String userName = requestBody.getString("userName");
            //外部ID
            String externalId = requestBody.getString("externalId");
            //用户的显示名称
            String displayName = requestBody.getString("displayName");
            //邮箱
        /*
        [{      
              “primary”: “true”,      
              “type”: “work”,      
              “value”:“de@idsmanager.com”    
          }]
         */
            JSONArray emails = requestBody.getJSONArray("emails");
            //手机号, 只能一个且唯一
        /*
        [{      
                  “type”: “work”,      
                  “value”: “”    
                }]
         */
            JSONArray phoneNumbers = requestBody.getJSONArray("phoneNumbers");


            //自定义扩展的字段
            /*
    "extendField":{
        "attributes":{
            "certno":"320402199011052528",
            "certtype":"1"
        },
        "description":"",
        "expireTime":"2116-12-31",
        "phoneRegion":"",
        "removeChildrenGroupExternalId":"",
        "removeGroupExternalId":"",
        "removeParentGroupExternalId":"",
        "udGroupExternalId":""
    }
             */
            JSONObject extendField = requestBody.getJSONObject("extendFields");
            Map<String, Object> attributes = (Map<String, Object>) extendField.get("attributes");
            //人员的排序字段
            String priority = "";
            if (attributes != null) {
                priority = (String) attributes.get("priority");
            }



        /*
        账户指定组织单位
        [{      
              “belongOuUuid”: “5088568925399532181”,      
              “ouDirectory”: “ /瀚华金融”,      
              “rootNode”: true    
            }]
         */
            JSONArray belongs = requestBody.getJSONArray("belongs");
            //是否禁用账户，true禁用，false启用账户,禁用账户后将不能登录应用系统
//            Boolean locked = requestBody.getBoolean("locked");
            Boolean enabled = requestBody.getBoolean("enabled");

            List<String> userDepartmentIdList = new ArrayList<>();

            if (belongs != null || belongs.size() != 0) {
                for (int i = 0; i < belongs.size(); i++) {
                    JSONObject deptjsonObject = belongs.getJSONObject(i);
                    DepartmentModel userOrgZi;
                    if (MAIN.equals(deptjsonObject.getString("belongOuUuid"))) {
                        userOrgZi = engineService.getOrganizationFacade().getDepartment(cloudpivotRootDeptId);
                    } else {
                        String s1 = "CP" + deptjsonObject.getString("belongOuUuid");
                        log.info("===========用户:{}，idaas需绑定部门====={}", displayName, s1);
                        userOrgZi = engineService.getOrganizationFacade().getDepartmentBySourceId(s1);
                    }
                    if (userOrgZi == null) {
                        log.info("===========用户:{}，查询不到idaas需绑定的部门====={}，跳过", displayName, deptjsonObject.getString("belongOuUuid"));
                        continue;
                    }
                    userDepartmentIdList.add(userOrgZi.getId());
                }
            }
            if (userDepartmentIdList.size() < 1) {
                log.info("===========用户:{}，查询不到idaas需绑定的部门，跳过此用户的新增", displayName);
                return;
            }


            JSONObject belongObj = belongs.size() > 0 ?
                    //Optional.ofNullable(belongs).get().getJSONObject(belongs.size() - 1) : new JSONObject();
                    Optional.ofNullable(belongs).get().getJSONObject(0) : new JSONObject();


            JSONObject emailObj = emails.size() > 0 ?
                    Optional.ofNullable(emails).get().getJSONObject(0) : new JSONObject();

            JSONObject phoneObj = phoneNumbers.size() > 0 ?
                    Optional.ofNullable(phoneNumbers).get().getJSONObject(0) : new JSONObject();


            //String s = "CP" + belongObj.getString("belongOuUuid");
            //log.info("===========用户:{}，部门====={}", displayName, s);
            //DepartmentModel userOrg = dubboConfigService.getOrganizationFacade().getDepartmentBySourceId(s);


            //String orgId = Optional.ofNullable(userOrg).orElse(new DepartmentModel()).getId();
            log.info("===========用户:{}，部门====={}====获取到云枢部门作为主部门", displayName, userDepartmentIdList.get(userDepartmentIdList.size() - 1));

            DepartmentUserModel departmentUserModel = new DepartmentUserModel();
            //该方法只能查询主组织下的用户
            UserModel user = engineService.getOrganizationFacade().getUserByUsername(userName);
            Boolean isAdd = Boolean.FALSE;
            //为空新增
            if (user == null) {
                isAdd = Boolean.TRUE;
                user = new UserModel();
                user.setCorpId("main");
                user.setLeader(false);
            }
            user.setUsername(userName);
            user.setName(displayName);
            user.setMobile(phoneObj.getString("value"));
            user.setEmail(emailObj.getString("value"));
            user.setStatus(enabled ? UserStatus.ENABLE : UserStatus.DISABLE);
            user.setEmployeeNo(id);
            user.setActive(enabled);
            user.setDeleted(!enabled);
            //user.setDepartmentId(userDepartmentIdList.get(userDepartmentIdList.size() - 1));
            //因idaas同步过来的数据问题，把部门的第一个作为主部门
            user.setDepartmentId(userDepartmentIdList.get(0));
            user.setSourceId("CP" + externalId);
            user.setUserId(id);
            user.setAdmin(false);
            OrganizationFacade organizationFacade = engineService.getOrganizationFacade();
            if (isAdd) {
                log.info("===idaas推送同步===用户=={},name=={}==走新增", displayName, userName);
                user.setCreatedTime(new Date());
                user.setModifiedTime(new Date());
                //在新增用户时才会重置默认密码
                user.setPassword(PasswordEncoderFactories.createDelegatingPasswordEncoder().encode("123456"));
                user = engineService.getOrganizationFacade().addUser(user);
            } else {
                log.info("===idaas推送同步===用户=={},name=={}==走更新", displayName, userName);
                //因涉及到用户多组织的情况，更新时将该用户在部门用户表数据的数据先删后增
                UserModel userModel = organizationFacade.updateUser(user);
                //先查该用户在部门用户表的数据
                List<DepartmentUserModel> departmentUsersByUserId = organizationFacade.getDepartmentUsersByUserId(userModel.getId());
                for (DepartmentUserModel model : departmentUsersByUserId) {
                    organizationFacade.removeDeptUser(model);
                }
            }

            //belongs 经过前置处理，不需要判空
            if (belongs.size() != 0) {
                for (int i = 0; i < userDepartmentIdList.size(); i++) {
                    departmentUserModel.setUserId(user.getId());
                    departmentUserModel.setCreatedTime(new Date());
                    departmentUserModel.setDeleted(false);
                    departmentUserModel.setLeader(false);
                    departmentUserModel.setDeptId(userDepartmentIdList.get(i));
                    if (StringUtils.isNotBlank(priority)) {
                        departmentUserModel.setSortKey(Long.valueOf(priority));
                    }
                    departmentUserModel.setMain(i == 0);
                    engineService.getOrganizationFacade().addDepartmentUser(departmentUserModel);
                }
            }
        } catch (Exception e) {
            log.error("===idaas推送同步====用户处理异常======{}", e.getMessage());
            throw new Exception("idaas推送同步用户,处理异常");
        }
    }
}
